<?php

declare (strict_types=1);
namespace App\Model;
use Hyperf\DbConnection\Db;

trait SelectTrait{

    //根据用户字段筛选用户
    public function scopeOfWxUser($query,$key,$value)
    {
        if(!empty($value)){
            // $ids=Wxuser::where($key,'like',"%$value%")->pluck('openid');
            // return $query->whereIn('openid',$ids);
            return $query->whereIn('openid',function($sql)use($key,$value){
                $sql->select('openid')->from('wxuser')->where($key,'like',"%$value%");
            });

        }   
    }

    public function scopeOfNickName($query,$value){
        if(!empty($value)){
            // $ids=Wxuser::whereRaw("from_base64(nickname) LIKE '%".$value."%'")->pluck('openid');
            return $query->whereIn('openid',function($sql)use($value){
                $sql->select('openid')->from('wxuser')->whereRaw("from_base64(nickname) LIKE '%".$value."%'");
            });
        }
    }

    //筛选用户
    public function scopeOfUser($query,$value)
    {
        return $query->where('openid',$value);
    }

    //通用筛选like方法
    public function scopeOfLikeField($query,$key,$value)
    {
        if(!empty($value)){
            return $query->where($key,'like',"%$value%");
        }   
    }

    //通用筛选like方法
    public function scopeOfEqField($query,$key,$value)
    {
        if(!empty($value)){
            return $query->where($key,$value);
        }   
    }

    //根据红包信息筛选红包
    public function scopeOfCoupon($query,$key,$value)
    {
   
        if(!empty($value)){
            // return $query->whereExists(function($sql) use($key,$value){
            //     $table=$this->table;
            //     $prefix=DB::getConfig('prefix');
            //     $sql->select(DB::raw(1))->from('coupon')->
            //     whereRaw("{$prefix}{$table}.coupon_id={$prefix}coupon.id AND {$prefix}coupon.{$key} like '%{$value}%' ");
            // }); 

            return $query->whereIn('coupon_id',function($sql)use($key,$value){
                $sql->select('id')->from('coupon')->where($key,'like',"%$value%");
            });
        }   
    }


}